package com.hoppinzq.service.controller;

import com.alibaba.fastjson.JSONObject;
import com.hoppinzq.service.ServiceProxyFactory;
import com.hoppinzq.service.bean.RPCPropertyBean;
import com.hoppinzq.service.bean.ServiceApiBean;
import com.hoppinzq.service.bean.User;
import com.hoppinzq.service.cache.apiCache;
import com.hoppinzq.service.common.UserPrincipal;
import com.hoppinzq.service.interfaceService.LoginService;
import com.hoppinzq.service.util.CookieUtils;
import com.hoppinzq.service.util.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(JarFileUploadController.class);

    @Autowired
    private RPCPropertyBean rpcPropertyBean;
    @Autowired
    private RedisUtils redisUtils;

    @ResponseBody
    @PostMapping("/getUser")
    public User getUser(String ucode, String token, HttpServletRequest request, HttpServletResponse response) throws InterruptedException {
        logger.debug("------------------------------------------------");
        logger.debug("getUser接口被调用");
        if(ucode!=null&&token==null){
            logger.debug("获取到了一次性ucode:"+ucode);
            UserPrincipal upp = new UserPrincipal(rpcPropertyBean.getUserName(), rpcPropertyBean.getPassword());
            LoginService loginService= ServiceProxyFactory.createProxy(LoginService.class, rpcPropertyBean.getServerAuth(), upp);
            User user =loginService.getUserByCode(ucode);
            if(user==null){
                token=null;
            }else{
                logger.debug("查询到了ucode对应的用户信息:"+ JSONObject.toJSONString(user));
                token=user.getToken();
                logger.debug("查询到了对应的用户信息的token:"+token);
                //设置token有效期
                logger.debug("写入值为:ZMANAGER:USER:"+token+"redis中");
                redisUtils.set("ZMANAGER:USER:"+token,user,7*24*60*60);
                return user;
            }
        }
        logger.debug("获取到当前用户的token："+token);
        if(token==null){
            logger.error("未获取到token，用户未登录过，");
            throw new RuntimeException("用户未登录");
        }
        User user = (User) redisUtils.get("ZMANAGER:USER:" +token);
        if (user==null) {
            logger.error("未获取到用户，token已过期");
            throw new RuntimeException("用户登录已过期");
        }
        logger.debug("获取到当前用户成功："+user);
        logger.debug("------------------------------------------------");
        return user;
    }

    @ResponseBody
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request,HttpServletResponse response){
        logger.debug("------------------------------------------------");
        logger.debug("logout接口被调用");
        logger.debug("有用户登出");
        String token = CookieUtils.getCookie(request,"ZQ_TOKEN");
        if(token!=null){
            logger.debug("获取到的token是:"+token);
            redisUtils.del("ZMANAGER:USER:"+token);
            logger.debug("从redis移除Key:ZMANAGER:USER:"+token);
            Cookie cookie = new Cookie("ZQ_TOKEN", "");
            logger.debug("清空Key为ZQ_TOKEN的cookie");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            logger.debug("用户开始下线");
            UserPrincipal upp = new UserPrincipal(rpcPropertyBean.getUserName(), rpcPropertyBean.getPassword());
            LoginService loginService= ServiceProxyFactory.createProxy(LoginService.class, rpcPropertyBean.getServerAuth(), upp);
            loginService.logout(token);
            logger.debug("用户下线，登出成功！");
            logger.debug("------------------------------------------------");
        }else{
            logger.debug("没有获取到token");
        }
    }

    @ResponseBody
    @RequestMapping("/apiParams")
    public JSONObject getServiceMessage(){
        JSONObject jsonObject=new JSONObject();
        List<ServiceApiBean> serviceApiBeans= apiCache.outApiList;
        jsonObject.put("api",serviceApiBeans);
        return jsonObject;
    }
}
